/*******************************************************************************
 * Copyright © 2010-2020  陈恩点版权所有
 * Author: 陈恩点
 * Last Updated: 2017/8/21 11:49:53
 * Contact: 18115503914
 * Description: MyRapid快速开发框架
*********************************************************************************/
using DevExpress.LookAndFeel;
using DevExpress.Skins;
using DevExpress.UserSkins;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraBars.Navigation;
using DevExpress.XtraEditors;
using DevExpress.XtraSplashScreen;
using DevExpress.XtraTabbedMdi;
using MyRapid.Base.Edit;
using MyRapid.Base.Page;
using MyRapid.Proxy;
using MyRapid.Proxy.MainService;
using MyRapid.Code;
using MyRapid.GlobalLocalizer;
using MyRapid.SysEntity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using static MyRapid.SysEntity.Sys_Enum;

namespace MyRapid.Client
{
    public partial class MainUI : MainPage
    {

        /// <summary>
        /// 当前用户
        /// </summary>
        /// 
        private Aut_User sys_User;

        /// <summary>
        /// 当前语言定位器
        /// </summary>
        private MyCommonLocalizer myCommonLocalizer = new MyCommonLocalizer();
        public MainUI()
        {

            #region 用户尝试登录系统
            if (BaseService.Session.SysUser == null)
            {
                UserLogin login = new Client.UserLogin();
                login.ShowDialog();
            }
            if (BaseService.Session.SysUser == null)
            {
                Process.GetCurrentProcess().Kill();
            }
            sys_User = BaseService.Session.SysUser;

            #endregion
            sw.Restart();
            #region 加载系统主界面
            try
            {
                #region InitializeComponent

                SplashScreenManager.ShowForm(this, typeof(WaitForm), false, false, false);
                InitializeAppearance();
                InitializeGlobalLocalizer();
                InitializeComponent();
                InitializeLauout();
                accTree.Elements.Clear();
                SkinHelper.InitSkinGalleryDropDown(mySkin);
                barUserNick.Caption = sys_User.User_Nick;
                InitializeCommonLocalizer();
                InitializeImage();
                InitializeMenu();
                #endregion
            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
                //Process.GetCurrentProcess().Kill();
            }
            #endregion
        }

        private void InitializeLauout()
        {
            try
            {
                object obj = CacheHelper.Get<object>("gcLeftWidth");
                int i = obj.ToIntEx();
                if (i > 0)
                    gcLeft.Width = i;
                obj = CacheHelper.Get<object>("gcRightWidth");
                i = obj.ToIntEx();
            }
            catch //(Exception ex)
            {

            }

        }



        /// <summary>
        /// 加载窗体控件语言
        /// </summary>
        private void InitializeCommonLocalizer()
        {
            this.Text = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MainUI_Text);
            barMenu.Hint = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_ShowHideMenuHint);
            barMenu.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_ShowHideMenu);
            barHelp.Hint = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_HelpHint);
            barHelp.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_Help);
            barUserNick.Hint = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_UserNickHint);
            barPageName.Hint = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_MenuNickHint);
            barAuther.Hint = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_AuthorHint);
            barVersion.Hint = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_VersionHint);
            barPageName.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_MenuNickHint);
            barAuther.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_AuthorHint);
            barVersion.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_VersionHint);
            barSkin.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_UserSkin);
            barSkin.Hint = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MenuCmd_UserSkinHint);

            barCloseThis.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.CloseMenu_This);
            barCloseOther.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.CloseMenu_Other);
            barCloseLeft.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.CloseMenu_Left);
            barCloseRight.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.CloseMenu_Right);
            barCloseAll.Caption = myCommonLocalizer.GetLocalizedString(MyCommonStringId.CloseMenu_All);

            BaseService.Session.Set("MainUI_Error", myCommonLocalizer.GetLocalizedString(MyCommonStringId.MainUI_Error));
            BaseService.Session.Set("ChildPage_Error", myCommonLocalizer.GetLocalizedString(MyCommonStringId.ChildPage_Error));
            BaseService.Session.Set("ChildPage_ConfirmCaption", myCommonLocalizer.GetLocalizedString(MyCommonStringId.ChildPage_ConfirmCaption));
            BaseService.Session.Set("ChildPage_ConfirmText", myCommonLocalizer.GetLocalizedString(MyCommonStringId.ChildPage_ConfirmText));
        }

        /// <summary>
        /// 窗体加载结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainUI_Shown(object sender, EventArgs e)
        {
            try
            {
                barTip.Caption = TimeDiff(sw);
                SplashScreenManager.CloseForm(false);
                this.Activate();
                BaseService.Session.Set("BarTip", barTip);
                //InitializeService();
            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
            }
        }

        Stopwatch sw = new Stopwatch();

        /// <summary>
        /// 计算时间差
        /// </summary>
        /// <param name="sw">计时器</param>
        /// <returns></returns>
        private string TimeDiff(Stopwatch sw)
        {
            try
            {
                sw.Stop();
                int M = sw.Elapsed.Milliseconds;
                int S = sw.Elapsed.Seconds;
                string sc = "{0}.{1}s";
                sc = String.Format(sc, S, M);
                return sc;
            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
                return string.Empty;
            }
        }

        private void MainUI_Load(object sender, EventArgs e)
        {
            try
            {

                smallIconList = (ImageCollection)BaseService.Session.Get("SmallIconList");
                largeIconList = (ImageCollection)BaseService.Session.Get("LargeIconList");
                myMdi.Images = smallIconList;
                accTree.Images = smallIconList;
                ShowMenu();
            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
            }
        }

        private void ShowMenu()
        {
            gcLeft.CustomHeaderButtons.Clear();
            List<Sys_Menu> MenuData = (List<Sys_Menu>)BaseService.Session.UserMenus;
            foreach (Sys_Menu menu in MenuData.Where(m => m.Menu_Parent == "0"))
            {
                DevExpress.XtraEditors.ButtonsPanelControl.GroupBoxButton btn = new DevExpress.XtraEditors.ButtonsPanelControl.GroupBoxButton();
                btn.Caption = menu.Menu_Nick;
                btn.Style = DevExpress.XtraBars.Docking2010.ButtonStyle.CheckButton;
                btn.UseCaption = false;
                btn.ToolTip = menu.Menu_Nick;
                btn.Tag = menu.Menu_Id;
                btn.Image = largeIconList.Images[menu.Menu_Icon];
                gcLeft.CustomHeaderButtons.Add(btn);
            }
            if (gcLeft.CustomHeaderButtons.Count > 0)
                gcLeft.CustomHeaderButtons[0].Properties.Checked = true;
        }

        private void gcLeft_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {

        }

        private void gcLeft_CustomButtonChecked(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            List<Sys_Menu> MenuData = (List<Sys_Menu>)BaseService.Session.UserMenus;
            string mid = e.Button.Properties.Tag.ToStringEx();
            if (string.IsNullOrEmpty(mid)) return;
            Sys_Menu sys_Menu = MenuData.Find(m => m.Menu_Id == mid);
            if (sys_Menu != null && !string.IsNullOrEmpty(sys_Menu.Menu_Id))
            {
                foreach (DevExpress.XtraEditors.ButtonsPanelControl.GroupBoxButton btn in gcLeft.CustomHeaderButtons)
                {
                    if (e.Button != btn)
                    {
                        btn.Checked = false;
                    }
                }
                accTree.Elements.Clear();
                foreach (Sys_Menu menu in MenuData.Where(m => m.Menu_Parent == e.Button.Properties.Tag.ToStringEx()))
                {
                    AccordionControlElement elt = new AccordionControlElement();
                    elt.Text = menu.Menu_Nick;
                    elt.Name = menu.Menu_Id;
                    elt.ImageIndex = menu.Menu_IconIndex;
                    if (MenuData.Find(m => m.Menu_Parent == menu.Menu_Id) == null)
                        elt.Style = ElementStyle.Item;
                    accTree.Elements.Add(elt);
                }
            }



        }

        private void accTree_ExpandStateChanged(object sender, ExpandStateChangedEventArgs e)
        {
            if (e.Element.Expanded)
            {
                e.Element.Elements.Clear();
                List<Sys_Menu> MenuData = (List<Sys_Menu>)BaseService.Session.UserMenus;
                foreach (Sys_Menu menu in MenuData.Where(m => m.Menu_Parent == e.Element.Name))
                {
                    AccordionControlElement elt = new AccordionControlElement();
                    elt.Text = menu.Menu_Nick;
                    elt.Name = menu.Menu_Id;
                    if (MenuData.Find(m => m.Menu_Parent == menu.Menu_Id) == null)
                        elt.Style = ElementStyle.Item;
                    elt.ImageIndex = menu.Menu_IconIndex;
                    e.Element.Elements.Add(elt);
                }
            }
        }

        /// <summary>
        /// 判断菜单是否已经打开
        /// </summary>
        /// <param name="sys_Menu">系统菜单</param>
        /// <returns>返回布尔值</returns>
        private bool IsMenuOpen(Sys_Menu sys_Menu)
        {
            try
            {

                foreach (XtraMdiTabPage tabPage in myMdi.Pages)
                {
                    ChildPage myPage = (ChildPage)tabPage.MdiChild;
                    Sys_Menu cys_Menu = myPage.SysMenu;
                    if (cys_Menu != null && cys_Menu.Menu_Id.Equals(sys_Menu.Menu_Id))
                    {
                        myMdi.SelectedPage = tabPage;
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
                return false;
            }
        }

        private string SearchFile(string filePath, string fileName)
        {
            if (Directory.Exists(filePath))
            {
                foreach (string fs in Directory.GetFiles(filePath, fileName))
                {
                    return fs;
                }
                foreach (string ds in Directory.GetDirectories(filePath))
                {
                    string sFile = SearchFile(ds, fileName);
                    if (!string.IsNullOrEmpty(sFile))
                    {
                        return sFile;
                    }
                }
            }
            return null;
        }

        public void OpenMenu(string menuId)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                sw.Restart();
                List<Sys_Menu> MenuData = (List<Sys_Menu>)BaseService.Session.UserMenus;
                Sys_Menu sys_Menu = MenuData.Find(m => m.Menu_Id == menuId);
                if (sys_Menu == null) return;
                if (string.IsNullOrEmpty(sys_Menu.Menu_Id)) return;
                if (!IsMenuOpen(sys_Menu))
                {
                    ChildPage myPage = SharedFunc.LoadMenu(sys_Menu);
                    SharedFunc.ShowMenu(myPage, this);
                }
                barTip.Caption = TimeDiff(sw);
                barTip.Hint = string.Empty;
            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }

        private void accTree_ElementClick(object sender, ElementClickEventArgs e)
        {
            try
            {
                OpenMenu(e.Element.Name);
            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void barHelp_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void barMenu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                gcLeft.Visible = !gcLeft.Visible;
                splitterControl1.Visible = !splitterControl1.Visible;

                InitializeMenu();
                ShowMenu();

            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
            }
        }

        private void MyMdi_PageAdded(object sender, MdiTabPageEventArgs e)
        {
            //MyStep.Visible = myMdi.Pages.Count == 0;
        }

        private void MyMdi_PageRemoved(object sender, MdiTabPageEventArgs e)
        {
            //MyStep.Visible = myMdi.Pages.Count == 0;
        }

        Sys_Menu CurMenu;
        private void MyMdi_SelectedPageChanged(object sender, EventArgs e)
        {
            try
            {
                GC.Collect();

                if (myMdi.SelectedPage != null)
                {
                    //Read_Sys_Help_ForMenu
                    ChildPage myPage = (ChildPage)myMdi.SelectedPage.MdiChild;
                    PushSession(myPage);
                    Sys_Menu sys_Menu = myPage.SysMenu;
                    if (sys_Menu != null)
                        CurMenu = sys_Menu;
                    myMdi.SelectedPage.ImageIndex = (int)sys_Menu.Menu_IconIndex;

                    if (myPage != null)
                    {
                        barPageName.Caption = sys_Menu.Menu_Nick;
                        barVersion.Caption = myPage.ProductVersion;
                        barAuther.Caption = sys_Menu.Menu_Nick;
                    }
                }
                else
                {
                    barPageName.Caption = string.Empty;
                    barVersion.Caption = string.Empty;
                    barAuther.Caption = string.Empty;
                }
            }
            catch (Exception ex)
            {
                SharedFunc.RaiseError(ex);
            }
        }






        /// <summary>
        /// 存入Session
        /// </summary>
        /// <param name="myPage"></param>
        /// <returns></returns>
        protected Storage PushSession(ChildPage myPage)
        {
            try
            {
                BaseService.Session.SysMenu = myPage.SysMenu;
                BaseService.Session.CurrForm = myPage;
                BaseService.Session.Set(myPage.Name, myPage);
                return BaseService.Session;
            }
            catch
            {
                throw;
            }
        }

        private void MainUI_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (BaseService.Session.UserMenus == null)
                return;
            string exitDetail = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MainUI_Exit);
            string exitText = myCommonLocalizer.GetLocalizedString(MyCommonStringId.MainUI_ExitDetail);
            if (XtraMessageBox.Show(exitText, exitDetail, MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                e.Cancel = true;
                return;
            }
            if (ModifierKeys == Keys.Control)
            {
                Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
            }
        }


        #region closeMenu
        private void MyMdi_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && ActiveMdiChild != null)
            {
                DevExpress.XtraTab.ViewInfo.BaseTabHitInfo hInfo = myMdi.CalcHitInfo(e.Location);
                //右键点击位置：在Page上且不在关闭按钮内
                if (hInfo.IsValid && hInfo.Page != null && !hInfo.InPageControlBox)
                {
                    this.closeMenu.ShowPopup(Control.MousePosition);//在鼠标位置弹出，而不是e.Location
                }
            }
        }
        //关闭当前
        private void barCloseThis_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.myMdi.SelectedPage.MdiChild.Close();
            //this.ActiveMdiChild.Close();
        }
        //关闭其他
        private void barCloseOther_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMdiTabPage xmp = this.myMdi.SelectedPage;
            while (this.myMdi.Pages[0] != xmp)
            {
                this.myMdi.Pages[0].MdiChild.Close();
            }
            while (this.myMdi.Pages[this.myMdi.Pages.Count - 1] != xmp)
            {
                this.myMdi.Pages[this.myMdi.Pages.Count - 1].MdiChild.Close();
            }
        }
        //关闭左边
        private void barCloseLeft_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMdiTabPage xmp = this.myMdi.SelectedPage;
            while (this.myMdi.Pages[0] != xmp)
            {
                this.myMdi.Pages[0].MdiChild.Close();
            }
        }
        //关闭右边
        private void barCloseRight_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMdiTabPage xmp = this.myMdi.SelectedPage;
            while (this.myMdi.Pages[this.myMdi.Pages.Count - 1] != xmp)
            {
                this.myMdi.Pages[this.myMdi.Pages.Count - 1].MdiChild.Close();
            }
        }
        //关闭所有
        private void barCloseAll_ItemClick(object sender, ItemClickEventArgs e)
        {
            while (this.myMdi.Pages.Count > 0)
            {
                this.myMdi.Pages[0].MdiChild.Close();
            }
        }

        #endregion

        private bool flag;
        private void MainUIEx_Activated(object sender, EventArgs e)
        {
            if (BaseService.IsFaulted)
            {
                BaseService.Session.SysUser = null;
            }
            sys_User = BaseService.Session.SysUser;
            if (sys_User != null)
            {
                barUserNick.Caption = BaseService.Session.SysUser.User_Nick;
            }
            else if (!flag)
            {
                flag = true;
                UserLogin login = new Client.UserLogin();
                login.ShowDialog();

            }
            if (BaseService.Session.SysUser == null)
            {
                Process.GetCurrentProcess().Kill();
            }
            sys_User = (Aut_User)BaseService.Session.SysUser;
        }
    }
}